require([ "dojo/dom-style", "dojo/_base/fx", "dojo/_base/declare", "dijit/registry", "dojo/dom" ], function(domStyle,
        fx, declare, registry, dom) {
    var Masker = declare(null, {
        overlayNode : null,
        constructor : function(nodeId) {
            this.overlayNode = dom.byId(nodeId);
        },
        endLoading : function() {
            fx.fadeOut({
                node : this.overlayNode,
                onEnd : function(node) {
                    domStyle.set(node, 'display', 'none');
                }
            }).play();
        }
    });
    loading = new Masker('loadingOverlay');
});

require([ "dojo/_base/lang", "dijit/layout/BorderContainer" ], function(lang) {
    loading.endLoading();
});

require([ "dijit/registry", "dojox/layout/ContentPane", "dojo/_base/array" ], function(registry, ContentPane, array) {
    openMenuLink = function(node) {
        var tabPanel = registry.byId('tabs');
        var url = node.menuurl || '';
        // 外部链接
        if (url.indexOf("http://") != -1 || url.indexOf("eweboffice") != -1) {
            var tabItem = registry.byId(node.menuid);
            var iframe = "<iframe frameborder='0' width='100%' height='100%' src='" + url + "'></iframe>";
            if (tabPanel.getIndexOfChild(tabItem) == -1) {
                var pane = new ContentPane({
                    id : node.menuid,
                    title : node.menuname,
                    content : iframe,
                    refreshOnShow : true,
                    closable : true
                });
                tabItem = pane;
                tabPanel.addChild(tabItem);
            }
            tabPanel.selectChild(tabItem);
        } else {
            // 内部链接
            var tabItems = tabPanel.getChildren();
            var existTabItem = null;
            array.forEach(tabItems, function(item, i) {
                var href = item.href;
                if (href == url) {
                    existTabItem = item;
                    return false;
                }
            });
            if (!existTabItem) {
                var pane = new ContentPane({
                    id : node.menuid || "227a-90a587e4734-37e2f5590f-7732",
                    title : node.menuname,
                    href : url,
                    refreshOnShow : true,
                    closable : true,
                    onDownloadError : function(error) {
                        if (error.status == '999') {
                            top.window.location = basePath + 'login/user';
                        } else {
                            return this.errorMessage;
                        }
                    }
                });
                tabPanel.addChild(pane);
                existTabItem = pane;
            }
            tabPanel.selectChild(existTabItem);
        }
    };
});

require([ "dojo/dom", "dijit/registry", "dojox/layout/ContentPane", "dojo/domReady!" ], function(dom, registry,
        ContentPane) {
    var filter = function(treeId, parentNode, childNodes) {
        if (!childNodes)
            return null;
        for ( var i = 0, l = childNodes.length; i < l; i++) {
            childNodes[i].menuname = childNodes[i].menuname.replace(/\.n/g, '.');
        }
        return childNodes;
    };
    var onClick = function(event, treeId, treeNode, clickFlag) {
        event.preventDefault();
        if (treeNode.isParent) {
            return;
        }
        openMenuLink(treeNode);
    };
    var setting = {
        async : {
            enable : true,
            url : "sysmenu/userMenus?userId=" + userid,
            autoParam : [ "menuid" ],
            dataFilter : filter
        },
        data : {
            key : {
                name : 'menuname',
                url : 'menuurl'
            },
            simpleData : {
                enable : true,
                idKey : 'menuid',
                pIdKey : 'pid'
            }
        },
        callback : {
            onClick : onClick
        }
    };
    jQuery.fn.zTree.init(jQuery("#menuTree"), setting);
});

require([ "dojo/parser", "dojo/ready", "dojo/_base/fx", "dojo/on", "dojo/has", "dojo/sniff" ], function(parser, ready,
        fx, on, has) {
    ready(function() {
        jQuery(document).keydown(function(e) {
            var doPrevent;
            if (e.keyCode == 8) {
                var d = e.srcElement || e.target;
                if (d.tagName.toUpperCase() == 'INPUT' || d.tagName.toUpperCase() == 'TEXTAREA') {
                    doPrevent = d.readOnly || d.disabled;
                } else {
                    doPrevent = true;
                }
            } else {
                doPrevent = false;
            }
            if (doPrevent) {
                e.preventDefault();
            }
        });
        if (has("ie") <= 7) { // only IE7 and below
            alert("为了更好体验效果, 请使用IE8及其以上浏览器！");
        }
        parser.parse();
    });
});

require([ "dojo/_base/fx", "dojo/dom", "dojo/dom-style", "dojox/av/FLAudio" ], function(fx, dom, domStyle, FLAudio) {
    // 与服务器指定事件交互 socket.emit($evtName$, $params$);
    var hostname = basePath.substring(0, basePath.lastIndexOf(':') + 1);
    // Connect SocketIo Server
    socket = io.connect(hostname + socketport, {
        'reconnection delay' : 2000,
        'force new connection' : true
    });
    mySound = new FLAudio({
        initialVolume : .8,
        autoPlay : false,
        isDebug : false
    });
    mySound.load({ url : "resources/MEDIA/sound/msg.mp3", id : "msg" });
    // Handler connect event
    socket.on('connect', function() {
        console.log('Client has connected to the server!');
        socket.emit('join', {
            userId : userid,
            username : username
        });
    });
    // Handler disconnect event
    socket.on('disconnect', function() {
        console.log('Client has disconnect to the server!');
    });
    // Handler server push messages
    socket.on('message', function(data) {
        msgNotifyWin.set("title", "<img src='resources/MEDIA/images/newpm.gif'  alt='新消息' />");
        if( msgNotifyWin.toggleable && !msgNotifyWin.open) {
            msgNotifyWin.toggle();
        }
        msgNotifyWin.set("content", data);
        mySound.doPlay({index:0, volume:1});
    });
    // Customer event
    sendMessage = function() {
        socket.send(dom.byId('subUserId').value);
    };
});

require([ "dojo/ready", "dojo/on" ], function(ready, on) {
    hideNotifyWin = function() {
        if( msgNotifyWin.toggleable && msgNotifyWin.open) {
            msgNotifyWin.toggle();
        }
    };
    syncNotifyWin = function() {
        msgNotifyWin.set("href", 'message/queryNewMsg');
    };
    openProcessTab = function() {
        var procMgrUrl = "documentprocess/mgr";
        openMenuLink({
            menuname : '收发文处理',
            menuurl : procMgrUrl
        });
        msgNotifyWin.set("title", "消息");
    };
});

require([ "dojo/_base/array", "dojo/dom", "dojo/dom-style", "dojo/on", "dojo/request", "dojo/json",
        "dijit/layout/StackContainer", "dijit/layout/ContentPane", "dijit/layout/StackController" ], function(array,
        dom, style, on, request, JSON, StackContainer, ContentPane, StackController) {
    // 上传组件
    uploadComponet = function(obj, realId) {
        var url = "attachcatalog/page?dropId=" + obj.id + "&keyId=" + realId;
        attachUploadPane.set("href", url);
        attachModal.show();
    };
    // 消息查看
    var initMsg = false;
    var sc = new StackContainer({
        style : "height: 180px; width: 320px;"
    }, "msgDetailContainer");
    var controller = new StackController({
        containerId : sc.id,
        onSelectChild : function(page) {
            if (!initMsg) {
                var msgPanels = sc.getChildren();
                var total = msgPanels.length;
                var cIndex = sc.getIndexOfChild(page) + 1;
                var type = cIndex >= total ? (total == 1 ? 'onePage' : 'lastPage') : (cIndex == 1 ? 'firstPage'
                        : 'middlePage');
                //console.log("共" + total + "页, 当前第" + cIndex + "页 , type=" + type);
                switch (type) {
                case 'onePage':
                    style.set("nextMsg", "display", "none");
                    style.set("previousMsg", "display", "none");
                    break;
                case 'lastPage':
                    style.set("previousMsg", "display", "");
                    style.set("nextMsg", "display", "none");
                    break;
                case 'firstPage':
                    style.set("nextMsg", "display", "");
                    style.set("previousMsg", "display", "none");
                    break;
                case 'middlePage':
                    style.set("nextMsg", "display", "");
                    style.set("previousMsg", "display", "");
                    break;
                default:
                    style.set("nextMsg", "display", "none");
                    style.set("previousMsg", "display", "none");
                    break;
                }
                var msg = { xxid : page.id, xxzt : 1 };
                request.post('message/update', {
                    data : JSON.stringify(msg),
                    headers : {
                        'Content-Type' : "application/json; charset=utf-8"
                    },
                    timeout : 30000
                }).then(function(response) {
                }, function(error) {
                    alert(error);
                });
            }
        }
    });
    msgDetailViewer = function() {
        // 动态获取
        request.post('message/queryAsList?paging=false&xxzt=0', {
            data : '',
            headers : {
                'Content-Type' : "application/json; charset=utf-8"
            },
            timeout : 30000
        }).then(function(response) {
            var resp = JSON.parse(response);
            array.forEach(resp, function(entry, i) {
                var content = "发送人:&nbsp;&nbsp;"+ entry.xxfsrxm+"<br/><br/> 内容:<br/><br/><span style='padding-left:1em;font-size: 2em;'>"+entry.xxnr||''+"</span>";
                sc.addChild(new ContentPane({
                    id : entry.xxid,
                    content : content
                }));
            });
            sc.startup();
            controller.startup();
            msgDetailDialog.show();
            // 去除遮罩层(none)|打开(block)
            dijit._underlay.domNode.style.display = "none";
        }, function(error) {
            alert(error);
        });
    };
    clearMsg = function() {
        array.forEach(sc.getChildren(), function(entry, i) {
            sc.removeChild(entry);
        });
    };
    msgShow = function() {
        initMsg = true;
        var total = sc.getChildren().length;
        if (total >= 2) {
            style.set("nextMsg", "display", "");
            style.set("previousMsg", "display", "none");
        } else {
            style.set("nextMsg", "display", "none");
            style.set("previousMsg", "display", "none");
        }
        if(sc.hasChildren()){
            var firt = sc.getChildren()[0];
            var msg = { xxid : firt.id, xxzt : 1 };
            request.post('message/update', {
                data : JSON.stringify(msg),
                headers : {
                    'Content-Type' : "application/json; charset=utf-8"
                },
                timeout : 30000
            }).then(function(response) {
            }, function(error) {
                alert(error);
            });
        }
    };
    on(dom.byId("nextMsg"), "click", function() {
        initMsg = false;
        sc.forward();
    });
    on(dom.byId("previousMsg"), "click", function() {
        initMsg = false;
        sc.back();
    });
});

require([ "dojo/dom", "dojo/query", "dijit/popup", "dojox/layout/ContentPane" ], function(dom, query, popup, ContentPane) {
    showUserTree = function(obj, realId) {
        var url = "sysuser/dropTree?dropId=" + obj.id + "&cType=" + (obj.ctype || obj.cType) + "&keyId=" + realId;
        var userdropTreePane = new ContentPane({
            href : url,
            style : 'width: 165px;height:250px;background: #f0f6e4;border: solid 1px #85B5D9;',
            onMouseLeave : function() {
                popup.close(this);
                this.destroy();
            },
            onClose : function() {
                popup.close(this);
                this.destroy();
            }
        });
        query("[dijitpopupparent|=\""+obj.id+"\"]").forEach(function(node){
            node.parentNode.removeChild(node);
        });
        popup.open({
            parent : obj,
            popup : userdropTreePane,
            around : obj.domNode
        });
        userdropTreePane.startup();
    };
});

require([], function() {
    DateFormat = function(pattern, formatSymbols) {
        if (pattern == null || pattern == undefined) {
            pattern = "yyyy-MM-dd HH:mm:ss SSS";
        }
        
        if (formatSymbols == null || formatSymbols == undefined) {
            formatSymbols = "yMdHmsS";
        }
        
        this.pattern = pattern;
        this.formatSymbols = formatSymbols;
    };
    DateFormat.prototype.parse = function(date) {
        var y = "";
        var M = "";
        var d = "";
        var H = "";
        var m = "";
        var s = "";
        var S = "";
        // 标记存入数组
        var cs = this.formatSymbols.split("");
        // 格式存入数组
        var ds = this.pattern.split("");
        // date = "2005-08-22 12:12:12 888";
        // format = "yyyy-MM-dd HH:mm:ss SSS";
        // sign = "yMdHmsS";
        var size = Math.min(ds.length, date.length);
        for ( var i = 0; i < size; i++) {
            switch (ds[i]) {
            case cs[0]: {
                y += date.charAt(i);
                break;
            }
            case cs[1]: {
                M += date.charAt(i);
                break;
            }
            case cs[2]: {
                d += date.charAt(i);
                break;
            }
            case cs[3]: {
                H += date.charAt(i);
                break;
            }
            case cs[4]: {
                m += date.charAt(i);
                break;
            }
            case cs[5]: {
                s += date.charAt(i);
                break;
            }
            case cs[6]: {
                S += date.charAt(i);
                break;
            }
            }
        }
        if (y.length < 1)
            y = 0;
        else
            y = parseInt(y);
        if (M.length < 1)
            M = 0;
        else
            M = parseInt(M);
        if (d.length < 1)
            d = 0;
        else
            d = parseInt(d);
        if (H.length < 1)
            H = 0;
        else
            H = parseInt(H);
        if (m.length < 1)
            m = 0;
        else
            m = parseInt(m);
        if (s.length < 1)
            s = 0;
        else
            s = parseInt(s);
        if (S.length < 1)
            S = 0;
        else
            S = parseInt(S);
        
        var d = new Date(y, M - 1, d, H, m, s, S);
        
        return d;
    };
});
